package com.framework.controller.newcontroller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.flow.FlowTask;
import com.framework.entity.tran.TranOrder;
import com.framework.service.AgentService;
import com.framework.service.FlowAccountService;
import com.framework.service.FlowTaskService;
import com.framework.service.TranOrderService;
import com.framework.utils.ali.AliPay;
import com.framework.utils.pay.youfupay.entity.PaymentTransResModle;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 回调
 *
 * @author ck
 * @date 2018/9/27 10:48
 */
@RestController
@Api(value="回调模块",tags={"回调模块"})
@RequestMapping("new")
public class NewPayCallbackController {


	@Autowired
	private FlowAccountService flowAccountService;

	@Autowired
	private TranOrderService tranOrderService;

	@Autowired
	private AgentService agentService;

	@Autowired
	private FlowTaskService flowTaskService;


	/**
	 * 支付宝订单回调
	 * @param requests
	 * @return
	 */
	@PostMapping(value = "notValidate/aliPaycallBack")
	@ApiOperation("支付回调")
	public String aliPaycallBack(HttpServletRequest requests){
		//1.从支付宝回调的request域中取值
		Map<String, String[]> requestParams = requests.getParameterMap();
		Map<String, String> params = new HashMap<>();
		System.out.println("从支付宝回调的request域中取值:requestParams===================================" + requestParams);
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		// 2.封装必须参数
		String outTradeNo = requests.getParameter("out_trade_no"); // 商户订单号
		System.err.println("out_trade_no==================================" + outTradeNo);
		String orderType = requests.getParameter("body"); // 订单内容
		System.out.println("orderType==================================" + orderType);
		String tradeStatus = requests.getParameter("trade_status"); // 交易状态
		System.err.println("tradeStatus=================================" + tradeStatus);
		// 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
		//boolean signVerified = false;
		//OrderType type = orderTypeService.queryOrderTypeByOrderNo(outTradeNo);
		//if(type.getState().intValue()==2){



		TranOrder order = tranOrderService.selectOne(new EntityWrapper<TranOrder>().eq("order_no", outTradeNo));

		//签名通过
		//if(signVerified){
			//成功订单
			if(!StringUtils.equals(tradeStatus,"WAIT_BUYER_PAY")){
				if(StringUtils.equals(tradeStatus,"TRADE_SUCCESS") || StringUtils.equals(tradeStatus,"TRADE_FINISHED")){
					//修改订单状态
					tranOrderService.successPayState(order.getOrderNo(),AliPay.ALI_PAY_TYPE);
					//添加账户流水日志
					FlowAccount account = new FlowAccount();
					account.setAgentId(order.getAgentId());
					account.setAccountType(2);
					account.setAmount(order.getGoodsPrice());
					account.setBelId(order.getOrderNo());
					account.setSupportType(1);
					flowAccountService.insertFlowAccount(account);
					//回调后购买成功推送
					tranOrderService.pushMessage(order);

					//如果采购大于等于300则另设等级
					if(order.getGoodsNumber().intValue()>=300){
						agentService.updateAgentGrade(order.getAgentId());
					}

				}if(StringUtils.equals(tradeStatus,"TRADE_CLOSED")){
					return "success";
				}
			}else{
				return "error";
			}

		//}
		//}
		// 只处理支付成功的订单:修改交易表状态,支付成功
		return "success";
	}

	/**
	 * 优付代付回调接口
	 *
	 * @param model
	 * @return
	 */
	/*@PostMapping(value = "notValidate/yfCallBack")
	@ApiOperation("优付代付回调接口")
	public Map<String, Object> yfCallBack(@RequestBody PaymentTransResModle model) {
		List<PaymentTransResModle.PayResultList> payResultList = model.getPayResultList();
		System.out.println(model.toString());

		for (PaymentTransResModle.PayResultList resultList : payResultList) {
			String resCode = resultList.getResCode();
			FlowTask flowTask = flowTaskService.queryFlowTaskByNo(resultList.getMerOrderId());
			flowTask.setTaskState("0000".equals(resCode) ? "success" : "fail");
			flowTask.setExplains("0000".equals(resCode) ? "成功" : "失败" + "--" + resultList.getResMsg());
			flowTaskService.updateById(flowTask);
		}

		Map<String, Object> result = new HashMap<>(2);
		result.put("resCode", "0000");
		result.put("resMsg", "成功");
		return result;
	}*/


}
